package com.example.todo.controller;

import com.example.todo.model.Knowledge;
import com.example.todo.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/knowledge")
@CrossOrigin(origins = "*")
public class KnowledgeController {

    private final KnowledgeService knowledgeService;

    @Autowired
    public KnowledgeController(KnowledgeService knowledgeService) {
        this.knowledgeService = knowledgeService;
    }

    @GetMapping
    public ResponseEntity<List<Knowledge>> getAllKnowledge() {
        List<Knowledge> knowledgeList = knowledgeService.findAll();
        return ResponseEntity.ok(knowledgeList);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Knowledge> getKnowledgeById(@PathVariable Long id) {
        Knowledge knowledge = knowledgeService.findById(id);
        if (knowledge != null) {
            return ResponseEntity.ok(knowledge);
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping
    public ResponseEntity<Knowledge> createKnowledge(@RequestBody Knowledge knowledge) {
        Knowledge createdKnowledge = knowledgeService.create(knowledge);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdKnowledge);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Knowledge> updateKnowledge(@PathVariable Long id, @RequestBody Knowledge knowledge) {
        Knowledge updatedKnowledge = knowledgeService.update(id, knowledge);
        if (updatedKnowledge != null) {
            return ResponseEntity.ok(updatedKnowledge);
        }
        return ResponseEntity.notFound().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteKnowledge(@PathVariable Long id) {
        knowledgeService.delete(id);
        return ResponseEntity.noContent().build();
    }
    
    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String imageUrl = knowledgeService.uploadImage(file);
            return ResponseEntity.ok(imageUrl);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("图片上传失败");
        }
    }
} 